using System;
using System.Linq;
using ExtendedMvc.Common.Diagnostics;
using ExtendedMvc.Html;

namespace ExtendedMvc.Elements {
	public abstract class VisibleElement<T> : Element<T> where T : VisibleElement<T> {
		private string _onClick;
		private string _onBlur;
		private string _onFocus;
		private string _onMouseOut;
		private string _onMouseOver;
		private string _onKeyPress;

		protected VisibleElement(string tag, string id = null)
			: base(tag, id) {
			Check.Argument.IsNotValid(tag, "tag", t => HtmlTag.Values.Contains(t));
		}

		public virtual T CssClass(string value) {
			if (!string.IsNullOrEmpty(value)) Builder.AddCssClass(value);
			return (T)this;
		}

		public virtual T Title(string value) {
			if (!string.IsNullOrEmpty(value)) SetAttribute(HtmlAttribute.Title, value);
			return (T)this;
		}

		public virtual T Styles(params Func<string, string>[] values) {
			var styles = values.Aggregate(string.Empty, (a, b) => a + (a == string.Empty ? "" : " ") + string.Format("{0}:{1};", b.Method.GetParameters()[0].Name.Replace('_', '-'), b(null)));
			if (!string.IsNullOrEmpty(styles)) MergeAttribute(HtmlAttribute.Style, styles);
			return (T)this;
		}

		#region Events
		public virtual T OnClick(string value) {
			_onClick = value;
			return (T)this;
		}

		public virtual T OnBlur(string value) {
			_onBlur = value;
			return (T)this;
		}

		public virtual T OnFocus(string value) {
			_onFocus = value;
			return (T)this;
		}

		public virtual T OnMouseOut(string value) {
			_onMouseOut = value;
			return (T)this;
		}

		public virtual T OnMouseOver(string value) {
			_onMouseOver = value;
			return (T)this;
		}

		public virtual T OnKeyPress(string value) {
			_onKeyPress = value;
			return (T)this;
		}
		#endregion

		protected override void Prepare() {
			if (!string.IsNullOrWhiteSpace(_onClick)) SetAttribute(HtmlEventAttribute.OnClick, _onClick);
			if (!string.IsNullOrWhiteSpace(_onBlur)) SetAttribute(HtmlEventAttribute.OnBlur, _onBlur);
			if (!string.IsNullOrWhiteSpace(_onFocus)) SetAttribute(HtmlEventAttribute.OnFocus, _onFocus);
			if (!string.IsNullOrWhiteSpace(_onMouseOut)) SetAttribute(HtmlEventAttribute.OnMouseOut, _onMouseOut);
			if (!string.IsNullOrWhiteSpace(_onMouseOver)) SetAttribute(HtmlEventAttribute.OnMouseOver, _onMouseOver);
			if (!string.IsNullOrWhiteSpace(_onKeyPress)) SetAttribute(HtmlEventAttribute.OnKeyPress, _onKeyPress);
			base.Prepare();
		}

	}
}